import { Injectable, UnauthorizedException, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport'
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from 'src/core/decorators/public.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector){
    super();
  }
  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }
    return super.canActivate(context);
  }
  //除非验证扩展request 里面的数据，一般不用处理 AuthGuard 已经处理好了
  // getRequest(context: ExecutionContext) {
  //   const ctx = context.switchToHttp();
  //   const request = ctx.getRequest();
  //   return request;
  // }

  // handleRequest 方法仅在身份验证成功或失败后被调用 先执行策略的validate方法
  handleRequest(err, user: any): any {
    if (err || !user) {
      throw new UnauthorizedException('身份验证失败');
    }
    return user;
  }
}